<?php

namespace app\common\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;
use think\facade\Cache;

/**
 * Throttle请求中间件
 * Class Throttle
 * @package app\api\middleware
 */
class Throttle
{
    public function handle($request, Closure $next)
    {
        $url = $request->pathinfo();
        $ip = $request->ip();
        $key = 'throttle_' . md5($url . $ip);
        $value = [
            'ip' => $ip,
            'url' => $url,
            'request_num' => 1,
        ];

        $cacheValue = Cache::store('file')->get($key);

        if (!$cacheValue) {
            Cache::store('file')->set($key, $value, 60);
        } else {
            if ($cacheValue['request_num'] > 20) {
                return error('请求太频繁了哦',429);

            } else {
                $cacheValue['request_num'] = $cacheValue['request_num'] + 1;
                Cache::store('file')->set($key, $cacheValue, 60);
            }
        }



        return $next($request);
    }
}